from .autoService import AutoService, log

if __name__ == '__main__':
    import sys

    if len(sys.argv) < 2:
        print("usage: python -m core.runner [moduleName].[[className].][flowName] args")
        print("example:python -m core.runner test.flow_login 123456")
        print("example:python -m core.runner test.TestA.flow_login 123456")
        exit(0)
    args = sys.argv[1].split(".")

    import importlib, inspect

    _cls = None  # type:
    _name = None
    flow_name = None
    if len(args) == 2:
        for name, cls in inspect.getmembers(importlib.import_module(args[0]), inspect.isclass):
            classes = cls.mro()
            if classes[0] == AutoService: continue
            if len(classes) < 3: continue
            if classes[-2] != AutoService: continue
            # index=str().find("AutoService")
            # if(index>0):
            _cls = cls
            _name = name
            flow_name = args[1]
            break
        if (_cls == None):
            print("自动装载类失败,类需要继承AutoService,否则需要手动传入")
            exit(0)
        # print(_cls)
        # print(_name)
        log("自动匹配到{}类".format(_name), model="multiRunner")
        # print()
    elif len(args) >= 3:
        for name, cls in inspect.getmembers(importlib.import_module(args[0]), inspect.isclass):
            classes = cls.mro()
            if classes[0] == AutoService: continue
            if len(classes) < 3: continue
            if classes[-2] != AutoService: continue
            if name != args[1]: continue

            # index=str().find("AutoService")
            # if(index>0):
            _cls = cls
            _name = name
            flow_name = args[2]
            break
        if (_cls == None):
            print("装载类失败,请手动检查类是否正确")
            exit(0)
    else:
        print("参数过多!")

    if _cls is not None:
        obj = None
        c = {"phoneNum": sys.argv[2]}
        try:
            obj = _cls.__new__(_cls)
            obj.__init__()
            getattr(obj, "init")(**c)
            getattr(obj, flow_name)()
            if hasattr(obj, "destroy"):
                getattr(obj, "destroy")()
        except Exception as e:
            if hasattr(obj, "errorCallBack"):
                getattr(obj, "errorCallBack")(e)
            else:
                log(e)
